package com.pm.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownFileUtils {

    /**
     * 下载PLM文件
     * @param urlStr
     * @param dir
     * @param response
     * @throws IOException
     */
    public static void downloadPLMFile(String urlStr, String dir, HttpServletResponse response) throws IOException {
        BufferedInputStream bis = null;
        OutputStream os = null;
        File file =null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(150000);
            connection.setReadTimeout(150000);
            connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            connection.setInstanceFollowRedirects(true); // 允许重定向
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                bis = new BufferedInputStream(url.openStream());
                file = new File(dir);
                File parentFile = file.getParentFile();
                if(!parentFile.exists()){
                    parentFile.mkdir();
                }
                if(!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream fis = new FileOutputStream(file);
                byte[] buffer1 = new byte[1024];
                int count=0;
                while((count = bis.read(buffer1,0,1024)) != -1)
                {
                    fis.write(buffer1, 0, count);
                }
                fis.close();

                FileInputStream in = new FileInputStream(file);
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Content-Disposition","attachment;filename=108.001.04741.zip");
                response.setCharacterEncoding("UTF-8");
                os = response.getOutputStream();
                byte[] buffer = new byte[1024];
                while(in.read(buffer) != -1)
                {
                    os.write(buffer);
                }
                os.flush();
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            os.close();
            bis.close();
            file.delete();
        }


    }
}
